﻿namespace Wilco.CodeHilighter.Engine
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Linq;
    using System.Web;
    using System.Xml.Linq;

    public static class Helper
    {
        #region Methods

        public static string GetAttributeValueFromElement(XElement elem, string parentNodeName, string elementNodeName, string attributeName, string attributeValue)
        {
            return (from c in elem.Descendants(parentNodeName)
                    where (c.Name == elementNodeName && c.Attributes().Where(
                                   attr => attr.Name == attributeName && attr.Value == attributeValue).FirstOrDefault() != null)
             select c.Value).FirstOrDefault();
        }

        public static XElement GetElemementByAttributeName(XElement elem, string parentNodeName, string elementNodeName, string attributeName,string attributeValue)
        {
            return (from c in elem.Descendants(parentNodeName)
                    where (c.Name == elementNodeName &&
                        c.Attributes().Where(
                            attr=>attr.Name==attributeName&&attr.Value == attributeValue).FirstOrDefault()!=null)
                    select c).SingleOrDefault();
        }

        public static string WriteEncodedText(string text)
        {
            if (text == null)
                return string.Empty;

            int length = text.Length;
            int startIndex = 0;
            string returnValue = text;
            while (startIndex < length)
            {
                int index = text.IndexOf('\x00a0', startIndex);
                if (index < 0)
                {
                    returnValue=HttpUtility.HtmlEncode((startIndex == 0) ? text : text.Substring(startIndex, length - startIndex));
                    startIndex = length;
                }
                else
                {
                    if (index > startIndex)
                    {
                        returnValue=HttpUtility.HtmlEncode(text.Substring(startIndex, index - startIndex));
                    }
                    returnValue+="&nbsp;";
                    startIndex = index + 1;
                }
            }
            return returnValue;
        }

        #endregion Methods
    }
}